<template>
  <form-dialop
    :title="action === 'edit' ? $t('common.editTenant') : $t('common.createTenant')"
    :visible="visible"
    width="30%"
    @handleClose="handleClose"
  >
    <template #content>
      <el-form ref="form" :model="formData" :rules="formRule" label-width="130px" v-loading="loading">
        <el-form-item :label="$t('common.name')" prop="name" style="padding-top: 18px;">
          <span class="form-explain">{{$t('message.tenantNameRule')}}</span>
          <el-input v-model="formData.name" :placeholder="$t('message.tenantName')" :disabled="action == 'edit'" @keyup.enter.native="submit"></el-input>
        </el-form-item>
        <!-- <el-form-item :label="$t('resource.DeletePassword')" prop="password" v-if="action === 'create'">
          <el-input type="password" show-password v-model="formData.password" :placeholder="$t('message.tenantPassword')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.confirmPassword')" prop="password" v-if="action === 'create'">
          <el-input type="password" show-password v-model="formData.re_password" :placeholder="$t('message.tenantConfirmPassword')"></el-input>
        </el-form-item> -->
        <el-form-item :label="$t('common.description')" prop="description">
          <el-input v-model="formData.description" type="textarea" maxlength="200" @keyup.enter.native="submit" show-word-limit :placeholder="$t('message.tenantDescription')"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="handleClose">{{$t('common.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :disabled="loading">{{$t('common.confirm')}}</el-button>
    </template>
  </form-dialop>
</template>
<script lang="ts">
import Vue from 'vue'
import FormDialop from '../../../components/Dialog/formDialog.vue';
export default Vue.extend({
  components: {
    FormDialop
  },
  props: {
    submitMethod: {
      type: Function,
      default() {
        return (action: any, formData: any) => Promise.resolve();
      }
    }
  },
  computed: {
    formRule() {
      const name = [
        { required: true, message: this.$t('message.tenantName'), trigger: 'blur' },
        { max: 50, message:  this.$t('message.nameLengthRule'), trigger: 'blur' },
        { validator: (rule: any, value: any, callback: any) => {
          (this as any).$tunnyApi.apiGetTenantList({}).then((res: Array<any>) => {
            if (res.findIndex((item) => item.name === value) !== -1 && (this.action !== 'edit' || value !== this.old_name)) {
              return callback(new Error(this.$t('message.nameOccupied').toString()));
            } else {
              return callback();
            }
          });
        }, trigger: 'blur' }
      ];

      const password = [
        { required: true, message: this.$t('user.passwordPlaceholder'), trigger: 'blur' },
        { max: 50, message: this.$t('message.passwordLengthRule').toString(), trigger: 'blur' }
      ];

      const re_password = [
        { validator: (rule: any, value: any, callback: any) => {
          if (value === '') {
            callback(new Error(this.$t('user.passwordRule.rePWEmpty').toString()));
          } else if (value !== (this as any).formData.password) {
            callback(new Error(this.$t('user.passwordRule.passwordDifferent').toString()));
          } else {
            callback();
          }
        }, trigger: 'blur' }
      ];

      const description = [
        { max: 200, message: this.$t('policy.message.descriptionLength').toString(), trigger: 'blur' }
      ];

      if (this.action === 'create') {
        return {
          name,
          password,
          re_password,
          description
        }
      } else if (this.action === 'edit') {
        return {
          name,
          description
        }
      } else {
        return {};
      }
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      action: "",
      old_name: "",
      formData: {
        name: "",
        password: "",
        re_password: "",
        description: ""
      }
    }
  },
  methods: {
    init(action: any, fromData: any) {
      this.loading = false;
      this.action = action;
      if (fromData) {
        this.formData = JSON.parse(JSON.stringify(fromData));
        this.old_name = fromData.name;
        this.visible = true;
      } else {
        this.formData = {
          name: "",
          // password: "",
          // re_password: "",
          description: ""
        };
        this.old_name = "";
        this.visible = true;
      }
      this.$nextTick(() => {
        (this.$refs as any).form.clearValidate();
      });
    },
    submit() {
      (this.$refs.form as any).validate((valid: any) => {
        if (valid) {
          this.loading = true;
          this.submitMethod(this.action, this.formData).then(() => {
            this.handleClose();
            this.$message({
              message: this.$t('desktopManage.message.operationSuccess', { operation: this.action === 'edit' ? this.$t('common.editTenant') : this.$t('common.createTenant')}).toString(),
              type: 'success'
            });
          }).catch(() => {
            this.$message({
              message: this.$t('desktopManage.message.operationFail', { operation: this.action === 'edit' ? this.$t('common.editTenant') : this.$t('common.createTenant')}).toString(),
              type: 'warning'
            });
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },
    handleClose() {
      this.formData = {
        name: "",
        // password: "",
        // re_password: "",
        description: ""
      };
      this.old_name = "";
      // this.action = "";
      this.loading = false;
      this.visible = false;
    }
  }
})
</script>

<style lang="scss" scoped>
.form-explain {
  color: #6F7D96;
  font-size: 12px;
  position: absolute;
  width: 100%;
  top: -24px;
  left: 0px;
}
</style>
